package com.amos.think.user.command;

import com.amos.think.common.exception.ThinkBizException;
import com.amos.think.domain.gateway.UserGateway;
import com.amos.think.domain.user.UserEntity;
import com.amos.think.dto.UserRegisterCmd;
import com.amos.think.dto.data.ErrorCode;
import com.amos.think.dto.data.UserVO;
import com.amos.think.service.mq.MessageService;
import com.amos.think.user.assembler.UserAssembler;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

/**
 * UserAddCmdExe
 */
@Component
public class UserRegisterCmdExe {

    @Autowired
    private UserGateway userGateway;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private MessageService messageService;
    public UserVO execute(UserRegisterCmd cmd){
        // check 用户名是否重复
        if (userGateway.checkByUsername(null, cmd.getUsername())) {
            throw new ThinkBizException(ErrorCode.B_USER_USERNAME_REPEAT);
        }
        try {
         messageService.sendJsonMessage("topic", UserAssembler.toEntity(cmd));
        }catch (Exception e){
            e.printStackTrace();
        }
//        UserEntity userEntity = userGateway.save(UserAssembler.toEntity(cmd));
        //将注册的用户信息存入到redis缓存中
        redisTemplate.opsForValue().set(cmd.getId(),cmd);
        return UserAssembler.toValueObject(UserAssembler.toEntity(cmd));
    }

}
